﻿#region LicenseHeader

// Copyright 2012 The Trustees of Indiana University.  All rights reserved.
// 
// The Indiana University licenses this file to you under the Apache License, 
// Version 2.0 (the "License"); you may not use this file except in compliance 
// with the License.  You may obtain a copy of the License at 
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
// See the License for the specific language governing permissions and 
// limitations under the License.
// 
// @author Thilina Gunarathne (tgunarat@indiana.edu)

#endregion

#region

using System;
using System.Data.Services.Client;
using System.Linq;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

#endregion

namespace AzureMRCore.DataModel
{
    public class JobDataContext : TableServiceContext
    {
        public string Name;

        public JobDataContext(string baseAddress, StorageCredentials credentials, string name)
            : base(baseAddress, credentials)
        {
            Name = name;
        }

        public IQueryable<JobDataModel> Jobs
        {
            get { return CreateQuery<JobDataModel>(Name); }
        }

        public Type ResolveEntityType(string name)
        {
            // if the context handles just one type, you can return it without checking the   
            // value of "name".  Otherwise, check for the name and return the appropriate   
            // type (maybe a map of Dictionary<string, Type> will be useful)         
            Type type = typeof (JobDataModel);
            return type;
        }

        public new DataServiceResponse SaveChangesWithRetries()
        {
            DataServiceResponse response;
            int retry = 0;

            retryLabel:
            try
            {
                response = SaveChanges();
            }

            catch (Exception e)
            {
                if (retry < Constants.NUM_RETRIES)
                {
                    retry++;
                    Thread.Sleep(100);
                    goto retryLabel;
                }
                else
                {
                    throw new Exception("save retry failed. retry " + retry, e);
                }
            }

            return response;
        }
    }
}